package top.infopub.util;


import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.ser.CustomSerializerFactory;


/**
 * 定义Spring的Json日期统一格式化
 * @author Awoke
 * @version 2018年9月25日
 * @see CustomDateObjectMapper
 * @since
 */
public class CustomDateObjectMapper extends ObjectMapper {

    public CustomDateObjectMapper() {
        CustomSerializerFactory factory = new CustomSerializerFactory();
        factory.addGenericMapping(Date.class, new JsonSerializer<Date>() {
            @Override
            public void serialize(Date value, JsonGenerator jsonGenerator,
                                  SerializerProvider provider)
                throws IOException, JsonProcessingException {
                // 格式化为yyyy/MM/dd 防止在部分浏览器使用js new Date(str)格式化时出现NaN的错误
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                jsonGenerator.writeString(sdf.format(value));
            }
        });
        this.setSerializerFactory(factory);
    }
}